package com.atguigu.controller;

import com.atguigu.exception.SleepUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/product")
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("lock")
    public String lock() throws Exception {
        RLock lock = redissonClient.getLock("lock");
        lock.tryLock(10,20, TimeUnit.SECONDS);
        String uuid = UUID.randomUUID().toString();
        SleepUtils.sleep(15);
        try {
            System.out.println(Thread.currentThread().getName() + "执行业务"+uuid);
        } finally {
            lock.unlock();
        }
        return Thread.currentThread().getName() + "执行业务"+uuid;
    }

    //测试写锁
    String uuid="";
    @GetMapping("write")
    public String write() throws Exception {
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("lock");
        RLock writeLock = rwLock.writeLock();
        try {
            writeLock.lock();
            SleepUtils.sleep(2);
            uuid=UUID.randomUUID().toString();
            System.out.println(Thread.currentThread().getName() + "执行业务"+uuid);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
        return Thread.currentThread().getName() + "执行业务"+uuid;
    }
    @GetMapping("read")
    public String read() throws Exception {
        RReadWriteLock rwLock = redissonClient.getReadWriteLock("lock");
        RLock readLock = rwLock.readLock();
        try {
            readLock.lock();
            return uuid;
        } finally {
            readLock.unlock();
        }
    }
}
